#!/bin/bash

# Torchooser is a hack to start TOT-Browser with a chosen URL. A list comes from a file named urls.
# Probably doesn't work anymore...

# If stdin is not a tty, start it in a terminal - unix.stackexchange.com/a/26691
if ! [ -t 0 ]; then
	term="${XTERMINAL-xterm}"
    case "$term" in
    xterm)
    "$term" -sh 1.3 -geometry 70x24 -T "${0##*/}" -e bash -c "$0 \"$@\"" "$@"
    ;;
    zutty)
    "$term" -geometry 70x24 -title "${0##*/}" -e bash -c "$0 \"$@\"" "$@"
    ;;
    *)
    "$term" -geometry 70x24 -T "${0##*/}" -e bash -c "$0 \"$@\"" "$@"
    ;;
    esac
fi

# if we have a command line argument, and it is "-x", then get content of clipboard
# otherwise use it as is...
[ -n "$1" ] && { [[ "$1" == "-x" ]] && str="$(xclip -o)" || str="$1"; }
# ... but only the 1st line
str="${str%%$'\n'*}"

torstart() {
    [ -z "$1" ] && return
    cd "$HOME/.local/share/torbrowser/tbb/x86_64/tor-browser_en-US/"
    ./start-tor-browser.desktop "$1"
}
array=()
helpy=()

if [ -n "$str" ]; then
    if [ -r "$str" ]; then
        mapfile -t array < "$str"
    else
        #~ while read line; do break; done <<<"$1"
        array=( "$str" "https://duckduckgo.com/?q=$str" "https://thepiratebay.org/search.php?video=on&q=$str" ) # only read until first newline
    fi
fi

for file in "$(dirname "$0")/urls" "$XDG_CONFIG_HOME/tor/urls"; do
    [ -r "$file" ] && mapfile -t helpy < "$file"
done

array=( "${array[@]}" "${helpy[@]}" )
# array with 2 colors and reset to normal
helpy=( "[94m" "[95m" "(B[m" )
# intersperse list with alternating colors
for ((i=0;i<${#array[@]};i++)); do ((i==${#array[@]}-1)) && array[i]="${array[i]}${helpy[2]}" || array[i]="${array[i]}${helpy[$((i%2))]}"; done

PS3="Choice: "

# Start with the 2nd color
printf '%s' "${helpy[1]}"
select url in "${array[@]}"; do
    # Remove escape sequences from back of Url:
    for i in "${helpy[@]}"; do url="${url%$i}"; done
    torstart "$url"
done
